package com.chai.controller;

import com.chai.domain.Book;
import com.chai.service.BookSerivce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    private BookSerivce bookSerivce;

    /**
     * 增加
     * */
    @PostMapping
    public Result save(@RequestBody Book book){
        boolean flag = bookSerivce.save(book);
        return new Result(flag? Code.SAVE_OK:Code.SAVE_ERR,flag,flag? "保存成功！":"保存失败");
    }

    /**
     * 根据id进行删除数据
     * */
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable int id){
        boolean flag = bookSerivce.deleteById(id);
        return new Result(flag? Code.DELETE_OK:Code.DELETE_ERR,flag,flag? "删除成功！":"删除失败");
    }

    /**
     * 修改数据
     * */
    @PutMapping
    public Result updateById(@RequestBody Book book){
        boolean flag = bookSerivce.update(book);
        return new Result(flag? Code.UPDATE_OK:Code.UPDATE_ERR,flag,flag? "修改成功！":"修改失败");
    }

    /**
     * 根据id进行查询
     * */
    @GetMapping("/{id}")
    public Result selectById(@PathVariable int id){
        Book book = bookSerivce.selectById(id);

        return new Result(book!=null? Code.GET_OK:Code.GET_ERR,book,book!=null? "查询成功":"查询失败！");
    }

    /**
     * 查询所有的数据
     * */
    @GetMapping
    public Result selectAll(){
        List<Book> books = bookSerivce.selectAll();
        return new Result(books!=null? Code.GET_OK:Code.GET_ERR,books,books!=null? "全部查询成功":"全部查询失败！");
    }
}
